#include "FilesAddProgress.h"
#include <QTimer>
#include <QDirIterator>
#include <QStringListModel>
#include <QTimerEvent> 

QFilesAddProgress::QFilesAddProgress(const QString& qsDirectory, const QStringList& qslException, QWidget *parent)
	: QDialog(parent)
	, m_qsDirectory(qsDirectory)
	, m_qslException(qslException)
{
	ui.setupUi(this);

	m_pFilesModel = new QStringListModel(this);
	ui.listViewFiles->setModel(m_pFilesModel);
	ui.listViewFiles->setEditTriggers(QAbstractItemView::NoEditTriggers);

	QStringList qslNameFilters;
	m_pDirIterator = new QDirIterator(m_qsDirectory,
		qslNameFilters,
		QDir::Files | QDir::NoSymLinks,
		QDirIterator::Subdirectories);

	m_nTimerIdAdd = startTimer(0);
	m_nTimerIdShow = startTimer(1000);

	connectSlots();
}

QFilesAddProgress::~QFilesAddProgress()
{
	killTimer(m_nTimerIdAdd);
	killTimer(m_nTimerIdShow);

	if (NULL != m_pDirIterator)
	{
		delete m_pDirIterator;
		m_pDirIterator = NULL;
	}
}

QStringList QFilesAddProgress::getFilesAdd() const
{
	return m_qslFilesAdd;
}

void QFilesAddProgress::connectSlots()
{
	connect(ui.pushButtonCancel, SIGNAL(clicked()), this, SLOT(pushButtonCancelSlotClicked()));
}

void QFilesAddProgress::timerEvent(QTimerEvent *event)
{
	if (event->timerId() == m_nTimerIdAdd)
	{
		if (m_pDirIterator->hasNext())
		{
			m_pDirIterator->next();
			QFileInfo file_info = m_pDirIterator->fileInfo();
			QString qsFilePath = file_info.filePath();
			if (!m_qslException.contains(qsFilePath))
			{
				m_qslFilesAdd.append(qsFilePath);
			}
		}
		else
		{
			accept();
		}
	}

	if (event->timerId() == m_nTimerIdShow)
	{
		m_pFilesModel->setStringList(m_qslFilesAdd);
		ui.listViewFiles->scrollToBottom();
	}
}

void QFilesAddProgress::pushButtonCancelSlotClicked()
{
	killTimer(m_nTimerIdAdd);
	killTimer(m_nTimerIdShow);
	reject();
}
